package middleware

import (
	"log"
	"net/http"
	"time"

	"gitee.com/yuwenlwl/comsdk/security"
)

// LoggingMiddleware 日志中间件
func LoggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		log.Printf("请求开始: %s %s", r.Method, r.URL.Path)

		next.ServeHTTP(w, r)

		log.Printf("请求结束: %s %s 耗时: %v", r.Method, r.URL.Path, time.Since(start))
	})
}

// GatewayAuthMiddleware API网关验证中间件
func GatewayAuthMiddleware(verifier security.Verifier) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if verifier != nil {
				isValid, err := verifier.VerifyGatewayRequest(r)
				if err != nil || !isValid {
					log.Printf("请求验证失败: %v", err)
					http.Error(w, "Unauthorized", http.StatusUnauthorized)
					return
				}
			}

			next.ServeHTTP(w, r)
		})
	}
}
